extends Control

@export var main_dialogue : Every_Singal_Dialogue_Group
@export var text_box : Label

@onready var panel: Panel = $Panel


var typing_tween : Tween
var fade_tween : Tween

var dialogue_kind : int = 0
var dialogue_part : int = 0 
var dialogue_index : int = 0
var is_mind : bool


func choose_dialogue_part(kind : int , part : int):
	visible = true
	dialogue_kind = kind
	dialogue_part = part
	
	displaye_next_talk_dialogue()


func displaye_next_talk_dialogue():
	
	#将当前对话类型拆包
	var dialogue01 := main_dialogue.every_singal_dialogue_group[dialogue_kind]
	#解析下一段该显示的是对话还是心声
	is_mind = dialogue01.is_mind
	
	#如果是对话，暂停场景
	if not is_mind:
		get_tree().paused = true
	else:
		panel.modulate.a = 0
	
	#将当前对话编号拆包
	var dialogue02 := dialogue01.every_dialogue_group[dialogue_part]
	
	#判断当前文本是否结束
	if dialogue_index >= len(dialogue02.dialogue_group):
		visible = false
		panel.modulate.a = 1.0
		get_tree().paused = false
		dialogue_index = 0
		return
	
	#将当前对话段的句子拆包
	var dialogue03 := dialogue02.dialogue_group[dialogue_index]
	
	#判定当前文本类型（心声/对话）
	if not is_mind:
		talk_display(dialogue03.content)
		
	else:
		mind_display(dialogue03.content)


func talk_display(text : String):
	#以打字机效果呈现文本
	if typing_tween and typing_tween.is_running():
		typing_tween.kill()
		text_box.text = text
		dialogue_index += 1 
	else:
		typing_tween = create_tween()
		text_box.text = ""
		
		for character in text:
			typing_tween.tween_callback(append_character.bind(character)).set_delay(0.06)
		typing_tween.tween_callback(func(): dialogue_index += 1)


func mind_display(text : String):
	#以淡入淡出效果呈现文本
	fade_tween = create_tween()
	text_box.text = text
	fade_tween.tween_property(panel, "modulate:a" , 1.0, 1.2)
	fade_tween.tween_property(panel, "modulate:a" , 0 , 1.5).set_delay(1.0)
	await fade_tween.finished
	dialogue_index += 1
	displaye_next_talk_dialogue()


func append_character(character : String):
	text_box.text += character
	fade_tween


func _physics_process(delta: float) -> void:
	if not is_mind and visible and (Input.is_action_just_pressed("conect") or Input.is_action_just_pressed("push_dialogue")):
		displaye_next_talk_dialogue()
